package interpret.demo1;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Hongliang Zhu
 * @create 2023-01-07 23:01
 */
public class ExpressionInterpreter {

    private Deque<Long> numbers = new LinkedList<>();

    /**
     * 解释执行
     *
     * @param expression 表达式
     * @return 运算结果
     */
    public long interpret(String expression) {

        String[] elements = expression.split(" ");
        int len = elements.length;

        for (int i = 0; i < (len + 1) / 2; ++i) {
            numbers.addLast(Long.parseLong(elements[i]));
        }

        for (int i = (len + 1) / 2; i < len; ++i) {
            String operator = elements[i];
            boolean isValid = "+".equals(operator) || "-".equals(operator) || "*".equals(operator) || "/".equals(operator);
            if (!isValid) {
                throw new RuntimeException("Expression is invalid: " + expression);
            }
            long number1 = numbers.pollFirst();
            long number2 = numbers.pollFirst();
            long result = 0;
            if (operator.equals("+")) {
                result = number1 + number2;
            } else if (operator.equals("-")) {
                result = number1 - number2;
            } else if (operator.equals("*")) {
                result = number1 * number2;
            } else if (operator.equals("/")) {
                result = number1 / number2;
            }
            numbers.addFirst(result);
        }
        if (numbers.size() != 1) {
            throw new RuntimeException("Expression is invalid: " + expression);
        }
        return numbers.pop();
    }

}
